package com.leetcode.first50;

import java.util.HashMap;
import java.util.Map;

public class LeetCode0013 {

    public static void main(String[] args) {
        LeetCode0013 leetCode0013 = new LeetCode0013();
        System.out.println(leetCode0013.romanToInt("I"));
        System.out.println(leetCode0013.romanToInt("III"));
        System.out.println(leetCode0013.romanToInt("IV"));
        System.out.println(leetCode0013.romanToInt("LVIII"));
        System.out.println(leetCode0013.romanToInt("MCMXCIV"));

    }

    public int romanToInt(String s) {

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("I", 1);
        map.put("V", 5);
        map.put("X", 10);
        map.put("L", 50);
        map.put("C", 100);
        map.put("D", 500);
        map.put("M", 1000);

        Map<String, Integer> nines = new HashMap<String, Integer>();
        nines.put("IV", 4);
        nines.put("IX", 9);
        nines.put("XL", 40);
        nines.put("XC", 90);
        nines.put("CD", 400);
        nines.put("CM", 900);

        int value = 0;
        int length = s.length();
        for (int index = 0; index < length; index++) {
            if (length - index > 1) {
                String header = s.substring(index, index + 2);
                if (nines.containsKey(header)) {
                    value += nines.get(header);
                    index++;
                    continue;
                }
            }
            Character ch = s.charAt(index);
            value += map.get(String.valueOf(ch));

        }
        return value;
    }
}
